package caculate.stack;

import java.util.*;

/**
 * @program: rocsun
 * @description:
 * @author: yx.guo
 * @create: 2025-04-14 18:59
 **/
public class EalRPN {

    public static String[] arr = {"+", "-", "*", "/"};
    public Set<String> set = new HashSet<>(Arrays.asList(arr));

    public int evalRPN(String[] tokens) {
        Deque<String> stack = new ArrayDeque<>();

        for(String s: tokens) {
            stack.push(s);
            checkCaculate(stack);
        }
        return Integer.parseInt(stack.pop());
    }

    public void checkCaculate(Deque<String> stack) {
        if (!set.contains(stack.peek())) {
            return;
        }

        String symbol = stack.pop();
        int v2 = Integer.parseInt(stack.pop());
        int v1 = Integer.parseInt(stack.pop());
        switch(symbol) {
            case "+": stack.push(String.valueOf(v1 + v2)); break;
            case "-": stack.push(String.valueOf(v1 - v2)); break;
            case "*": stack.push(String.valueOf(v1 * v2)); break;
            case "/": stack.push(String.valueOf(v1 / v2)); break;
            default:
                throw new RuntimeException("符号错误！");
        }
    }

}
